package com.zy.service.bs.impl;

import com.zy.pojo.exceptions.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zy.dao.bs.LableDao;
import com.zy.entity.enums.StatusEnum;
import com.zy.entity.bs.Lable;
import com.zy.pojo.query.bs.LableQuery;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.LableService;
import com.zy.utils.DateUtil;
import tk.mybatis.mapper.entity.Example;

@Service("lableService")
public class LableServiceImpl extends BaseServiceImpl<Lable> implements LableService {

	@Autowired
	private LableDao lableDao;

	@Override
	public PageVo pageLable(LableQuery lableQuery, Integer start, Integer limit) {
		return new PageVo(start, limit, this.lableDao.countLable(lableQuery), this.lableDao.listLable(lableQuery, start, limit));
	}

	@Override
	public void saveLable(Lable lable) {
		lable.setId(null);
		existsName(lable);
		long time = DateUtil.getTime();
		lable.setCreateTime(time);
		lable.setModifyTime(time);
		lable.setStatus(StatusEnum.NORMAL.getValue());
		this.lableDao.save(lable);
	}
	
	@Override
	public void updateLable(Lable lable) {
		existsName(lable);
		lable.setModifyTime(DateUtil.getTime());
		this.lableDao.updateByPrimaryKeySelective(lable);
	}

	@Override
	public void removeLable(long id) {
		try {
			this.lableDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			Lable lable = new Lable();
			lable.setId(id);
			lable.setModifyTime(DateUtil.getTime());
			lable.setStatus(StatusEnum.DELETE.getValue());
			this.lableDao.updateByPrimaryKeySelective(lable);
		}
	}

	@Override
	public void recover(long id) {
		Lable lable = new Lable();
		lable.setId(id);
		lable.setModifyTime(DateUtil.getTime());
		lable.setStatus(StatusEnum.NORMAL.getValue());
		this.lableDao.updateByPrimaryKeySelective(lable);
	}
	private void existsName(Lable lable) {
		Example ex = new Example(Lable.class);
		Example.Criteria cr = ex.createCriteria();
		cr.andEqualTo("name", lable.getName());
		cr.andEqualTo("lableTypeId", lable.getLableTypeId());
		Lable pojo = lableDao.getByExample(ex);
		if (pojo != null && !pojo.getId().equals(lable.getId())) {
			throw new ServiceException(lable.getName()+"重复标签");
		}

	}

}
